/**
 * 
 * @param {*浅拷贝} obj 
 * 复制每一个属性和它的值，若这个值是一个复杂类型，则只会拷贝其引用
 */
function shallowCopy(obj){
    let newobj = {};
    for(let key in obj){
        newobj[key] = obj[key];
    }
    return newobj;
}
let person = {
    name:"hh",
    age:10,
    sayName:function(){
        console.log(this.name);
    },
    familys:{
        father:"hhh",
        mother:"ashdg"
    },
    [Symbol.iterator](){
        let index=0;
        return {
            next(){
                if(index < 3){
                    return {value:index++,done:false}
                }else{
                    return {value:undefined,done:true}
                }
            }
        }
    }
}

for(let x of person){
    console.log(x);
}
let p = shallowCopy(person);
// p.familys.father = "xxx";
// console.log(p);

/***
 * 深拷贝,防止引用层数过多
 */
//使用for in 获取不到Symbol的键值对
function deepCopy(obj,deeplevel){
    deeplevel = deeplevel || 0;
    let newobj = {};
    for(let key in obj){
        if(typeof obj[key] === 'object' && deeplevel < 4){
            newobj[key] = deepCopy(obj[key],deeplevel+1);
        }else{
            newobj[key] = obj[key]; 
        }
    }
    return newobj;
}
//采用JSON的字符串方法和解析方法进行深度拷贝
function deepCopy1(obj){
    let newobj = JSON.parse(JSON.stringify(obj));
    return newobj;
}

//推荐使用这种方式进行深拷贝
function deepCopy(obj){
    function isObject(o){
        return (typeof obj === 'object' || typeof obj === 'function') && obj !==null
    }
    if(!isObject(obj)){
        throw new Error("不是对象");
    }
    let newobj = Array.isArray(obj)?[]:{};
    //返回由目标对象的自身属性键组成的 Array。。
    //包括Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))。
    Reflect.ownKeys(obj).forEach(key=>{
        newobj[key] = isObject(obj[key])?deepCopy(obj[key]):obj[key]; 
    })
    return newobj;
}

let p2 = deepCopy1(person);

// p2.familys.father = 'xixixi';
// console.log(p2);
// console.log(person);



